/*
 * @Author: WangLi
 * @Date: 2021-08-03 22:37:13
 * @LastEditors: WangLi
 * @LastEditTime: 2021-08-04 23:34:41
 * @Description:
 */
import { toPromise } from "../../../utils/util";
Component({
  externalClasses: ["custom-class"],
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    title: String,
    message: String,
    className: String,
    customStyle: String,
    overlayStyle: String,
    closeOnClickOverlay: Boolean,
    messageAlign: String,
    beforeClose: null,
    width: null,
    zIndex: {
      type: Number,
      value: 2000,
    },
    overlay: {
      type: Boolean,
      value: true,
    },
    transition: {
      type: String,
      value: "scale",
    },
    confirmButtonText: {
      type: String,
      value: "确认",
    },
    cancelButtonText: {
      type: String,
      value: "取消",
    },
    showConfirmButton: {
      type: Boolean,
      value: true,
    },
    showCancelButton: {
      type: Boolean,
      value: false,
    },
  },
  data: {
    loading: false,
    callback: () => {},
  },
  methods: {
    alert(options) {
      return this.handler(options);
    },
    confirm(options) {
      return this.handler(Object.assign({ showCancelButton: true }, options));
    },
    handler(options) {
      return new Promise((resolve, reject) => {
        this.setData({
          callback: (action, instance) => {
            action === "confirm" ? resolve(instance) : reject(instance);
          },
          ...options,
        });

        wx.nextTick(() => {
          this.setData({ show: true });
        });
      });
    },
    onClickOverlay() {
      this.close("overlay");
    },
    onCancel() {
      this.handleAction("cancel");
    },
    onConfirm() {
      this.handleAction("confirm");
    },
    close(action) {
      this.setData({ show: false });
      wx.nextTick(() => {
        this.triggerEvent("close", action);
        const { callback } = this.data;
        if (callback) {
          callback(action, this);
        }
      });
    },
    handleAction(action) {
      this.triggerEvent(action, { dialog: this });

      const { beforeClose } = this.data;
      if (!beforeClose) {
        this.close(action);
        return;
      }

      if (action === "confirm") {
        this.setData({
          loading: true,
        });
        toPromise(beforeClose(action)).then((value) => {
          if (value) {
            this.close(action);
          }
          this.stopLoading();
        });
      } else {
        this.close(action);
      }
    },
    stopLoading() {
      this.setData({
        loading: false,
      });
    },
  },
});
